import Taro, { Component, useState, useCallback } from '@tarojs/taro'
import styles from './index.module.scss'
import { View, Text, Input, Picker, Image } from '@tarojs/components'
import { AtButton, AtIcon } from 'taro-ui'
import { useSelector } from '@tarojs/redux'
import { dialog } from '@/util'
import { MINX_URL } from '@/api/config'
import { certificateUpload } from '@/api/index'


const CentificateUpload = () => {
  const [ name, setName ] = useState('')
  const [ date, setDate ] = useState('')
  const [ imgUrl, setImgUrl ] = useState('')
  const [ disabledBtn, setDisabledBtn ] = useState(false)
  const user = useSelector(state => state.user)
  const { info } = user
  const { mobile } = info
  const handlerChooseImage = () => {
    Taro.chooseImage({
      count: 1,
      sourceType: ['album'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0]
        handlerUpload(tempFilePaths)
      },
      fail(e) {
        console.log(e.errMsg)
      }
    })
  }
  const handlerUpload = (url) => {
    Taro.uploadFile({
      url: MINX_URL('/common/upload'),
      filePath: url,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      success(res) {
        console.log(res)
        if (res.statusCode === 200) {
          const result = JSON.parse(res.data)
          if (result.code === 0) {
            setImgUrl(result.url)
          }
        } else {
          dialog.toast({title: '上传失败'})
        }
      },
      fail(e) {
        dialog.toast({title: e.errMsg})
      }
    })
  }
  const uploadInfo = async () => {
    try {
      const { data } = await certificateUpload({phone: mobile, name, getTime: date, adresses: imgUrl})
      Taro.showToast({title: '提交成功，正在审核中..', duration: 3000, icon: 'none'})
      setTimeout(() => {
        setDate('')
        setImgUrl('')
        setName('')
        Taro.navigateBack()
      }, 3000);
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }
  const confirmOrder = () => {
    if (!name) return dialog.toast({title: '请输入证书名称'})
    if (!date) return dialog.toast({title: '请选择获得时间'})
    if (!imgUrl) return dialog.toast({title: '请上传证书'})
    setDisabledBtn(true)
    setTimeout(() => {
      setDisabledBtn(false)
    }, 3000);
    uploadInfo()
  }
  return (
    <View className={styles.wrapper}>
      <View className={styles.title}>人工上传证书资质</View>
      <View className={styles.info}>人工提交证书，平台需要审核资质，审核通过后，会在您的个人证书显示您拥有的证书。</View>
      <View className={styles.inputWrapper}>
        <View className={styles.label}>证书名称</View>
        <View className={`${styles.value}`}>
          <Input placeholder="请输入证书名称" onInput={(e) => {setName(e.detail.value)}} value={name}/>
        </View>
      </View>
      <View className={styles.inputWrapper}>
        <View className={styles.label}>获得时间</View>
        <View className={`${styles.value}`}>
          <Picker mode="date" onChange={(e) => {setDate(e.detail.value)}} onCancel={() => {}}>
            <Input placeholder="请选择获得时间" disabled value={date}/>
          </Picker>
        </View>
      </View>
      <View className={styles.inputWrapper}>
        <View className={styles.label}>上传证书</View>
        <View className={`${styles.value}`}>
          {
            imgUrl ?
            <View className="at-row at-row__align--center">
              <Image src={imgUrl} className={`at-col at-col-9 ${styles.img}`} mode="aspectFit"></Image>
              <AtIcon value="close" size="16" onClick={() => {setImgUrl('')}} className={`at-col ${styles.close}`}></AtIcon>
            </View> : <AtButton type="primary" size="small" className={styles.uploadBtn} onClick={handlerChooseImage}>选择附件</AtButton>
          }
        </View>
      </View>
      <AtButton type="primary" className={styles.submit} onClick={confirmOrder} disabled={disabledBtn}>提 交</AtButton>
    </View>
  )
}

CentificateUpload.config = {
  navigationBarTitleText: '证书上传'
}

export default CentificateUpload
